﻿using FirstFloor.ModernUI.Presentation;
using FirstFloor.ModernUI.Windows.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Microsoft.Practices.Unity;
using appCtx = EasyInvoice.ApplicationContext.AppContext;

namespace EasyInvoice.WPF.ViewModel
{
    public class ClientListViewModel : NotifyPropertyChanged
    {

        private string _name = string.Empty;

        private bool? _CanIssueInvoices;

        private Services.ClientsService _serviceClients; 

        public string Name
        {
            get
            {
                return this._name;
            }
            set
            {
                this._name = value;
                this.OnPropertyChanged("Name");
            }
        }

        public bool? CanIssueInvoices
        {
            get
            {
                return this._CanIssueInvoices;
            }
            set
            {
                this._CanIssueInvoices = value;
                OnPropertyChanged("CanIssueInvoices");
            }
        }

        
        public Uri SelectedLink { get; set; }

        public LinkCollection ClientLinks
        {
            get 
            {
                return new LinkCollection(from ClientViewModel client in GetClients() 
                                          select new Link() 
                                            { 
                                                DisplayName = client.Name, 
                                                Source = new Uri(client.Id.ToString() , UriKind.Relative)
                                            }
                                            );
            }
        }

        private ObservableCollection<ClientViewModel> GetClients()
        {
            var returnValue = new ObservableCollection<ClientViewModel>();
            var clients = this._serviceClients.GetAll();

            clients = from Model.Client c in clients
                      where c.Name.ToUpperInvariant().Contains(_name.ToUpperInvariant())
                      select c;

            if (this._CanIssueInvoices.HasValue)
                clients = from Model.Client c in clients
                          where c.IsMaster == this._CanIssueInvoices
                          select c;
            clients.ToList().ForEach(client => returnValue.Add(new ClientViewModel(client)));
            return returnValue;
        }

        public ClientListViewModel()
        {
            _serviceClients = appCtx.Instance.IoC.Resolve<Services.ClientsService>();
        }

        //private  void SetLinks()
        //{
          
        //    foreach (ClientViewModel client in GetClients())
        //    {
        //        try
        //        {
        //            Link link = new Link();
        //            link.DisplayName = client.Name;
        //            Uri uri = new Uri(client.Id.ToString(), UriKind.Relative);
        //            link.Source = uri;
        //            clientLinks.Add(link);
        //        }
        //        catch (Exception ex)
        //        {
        //            throw ex;
        //        }
        //    }
        //}


        private ICommand showAddCommand;

        public ICommand ShowAddCommand
        {
            get
            {
                if (showAddCommand == null)
                {
                    showAddCommand = new Common.CommandBase(
                        i => this.AddClient(), 
                        i => ((UserViewModel)Properties.Settings.Default.AuthenticatedUser)!=null?((UserViewModel)Properties.Settings.Default.AuthenticatedUser).AddClients:false);
                }
                return showAddCommand;
            }
        }

        private void AddClient()
        {
            SelectedLink = new Uri(string.Format("0|{0}", DateTime.Now.Ticks), UriKind.Relative);
            this.OnPropertyChanged("SelectedLink");
        }

        //for opening up the Delete Client window
        private ICommand showDeleteCommand;

        public ICommand ShowDeleteCommand
        {
            get
            {
                if (showDeleteCommand == null)
                {
                    showDeleteCommand = new Common.CommandBase(
                        i => this.DeleteClient(),
                        i => this.CanDelete());
                }
                return showDeleteCommand;
            }
        }

        private void DeleteClient()
        {
            ClientViewModel client = new ClientViewModel(this._serviceClients.Get(Convert.ToInt32(SelectedLink.ToString())));
            var result = ModernDialog.ShowMessage(string.Format("Do you want to delete client {0} ?", client.Name), "Delete Client Dialog", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    client.Delete();
                    if (ClientLinks.Count>0) SelectedLink = ClientLinks.First().Source;
                }
                catch (Exception ex)
                {
                    ModernDialog.ShowMessage(ex.Message, "Delete Client Failed", MessageBoxButton.OK);
                }
            }
            this.OnPropertyChanged("ClientLinks");
            this.OnPropertyChanged("SelectedLink");

        }

        private bool CanDelete()
        {
            if (object.Equals((UserViewModel)Properties.Settings.Default.AuthenticatedUser, null)) return false;
            if (object.Equals(SelectedLink, null)) return false;
            if (SelectedLink.OriginalString.Contains("|")) return false;
            return ((UserViewModel)Properties.Settings.Default.AuthenticatedUser).DeleteInvoices;
        }

        private ICommand refreshCommand;

        public ICommand RefreshCommand
        {
            get
            {
                if (refreshCommand == null)
                {
                    refreshCommand = new Common.CommandBase(i => this.RefreshClients(), null);
                }
                return refreshCommand;
            }
        }

        private void RefreshClients()
        {
            //save client
            this.OnPropertyChanged("ClientLinks"); 
        }
    }
}
